package com.heima.wemedia.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmLoginDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmLoginDto dto) {
       //1.判断用户名和密码是否为空
        if (StringUtils.isNotBlank(dto.getName())&&StringUtils.isNotBlank(dto.getPassword())){
            //1.1根据用户名查询用户
            WmUser wmUser = this.lambdaQuery().eq(WmUser::getName, dto.getName()).one();

            //1.2如果用户不存在则响应数据返回用户不存在
            if(wmUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }

            //1.3存在则查询密码是否正确,不正确返回密码错误
            boolean result = BCrypt.checkpw(dto.getPassword(),wmUser.getPassword());
            if (!result){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }

            //1.4正确则响应返回数据
            String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
            Map<String, Object> map = new HashMap<>();
            map.put("user", wmUser);
            map.put("token",token );
            return ResponseResult.okResult(map);
        }

        //2.游客登录
        String token = AppJwtUtil.getToken(0L);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token );
        return ResponseResult.okResult(map);

    }
}